<?php defined('SYSPATH') or die('No direct script access.');

class Model_Person extends ORM
{
	protected $_sorting = array('name' => 'ASC');
	
	protected $_has_many = array(
		'variants' => array(),
	);
	
	public function birth_date()
	{
		return $this->format_date($this->birth_date);
	}
	
	public function death_date()
	{
		return $this->format_date($this->death_date);
	}
	
	public function catalogs()
	{
		$catalogs = array();
		
		foreach($this->variants->find_all() as $v)
			$catalogs[] = $v->catalog;
			
		$catalogs = array_unique($catalogs);
		sort($catalogs);
		
		return $catalogs;
	}
	
	private function format_date($date_str)
	{
		$months = array('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
		list($year, $month, $date) = explode('-', $date_str);
		
		if((int)$year == 0)
			return '-';
		else if((int)$month == 0)
		{
			return $year;
		}
		else if((int)$date == 0)
		{
			return $months[(int)$month]." $year";
		}
		else
		{
			return date("jS M Y", strtotime($date_str));
		}
	}
	
	public function name_with_highlights($search)
	{
		if(empty($search))
			return $this->name;
			
		$parts = explode(" ", $search);
		
		$string = $this->name;
		
		foreach($parts as $p)
			$string = preg_replace("/($p)/i", '<span class="hl">$1</span>', $string);
			
		return $string;
	}
}